package whu.cn.whushare.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class TimeUtil {
	public static String getTimeString(long timeMillis, String format) {
		SimpleDateFormat sf = new SimpleDateFormat(format);
		return sf.format(timeMillis);
	}

	public static String getTimeString(Date date, String format) {
		SimpleDateFormat sf = new SimpleDateFormat(format);
		return sf.format(date);
	}

	public static long getTimeInMillis(String timeStr, String format) {
		SimpleDateFormat sf = new SimpleDateFormat(format);
		try {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(sf.parse(timeStr));
			return calendar.getTimeInMillis();
		} catch (ParseException e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static String formatSameDayOrSameYearDate(long then) {
		return formatSameDayOrSameYearDate(then, System.currentTimeMillis());
	}

	public static String formatSameDayOrSameYearDate(long then, long now) {
		SimpleDateFormat simpleDateFormat;

		Calendar pastCal = new GregorianCalendar();
		pastCal.setTimeInMillis(then);
		Date pastDate = pastCal.getTime();
		Calendar nowCal = new GregorianCalendar();
		nowCal.setTimeInMillis(now);

		if (pastCal.get(Calendar.YEAR) != nowCal.get(Calendar.YEAR)) {
			simpleDateFormat = new SimpleDateFormat("yy-MM-dd");
		} else if (pastCal.get(Calendar.MONTH) != nowCal.get(Calendar.MONTH)
				|| pastCal.get(Calendar.DAY_OF_MONTH) != nowCal.get(Calendar.DAY_OF_MONTH)) {
			simpleDateFormat = new SimpleDateFormat("MM-dd");
		} else
			simpleDateFormat = new SimpleDateFormat("H:mm");

		return simpleDateFormat.format(pastDate);
	}
}
